package cn.com.dhcc.turbo.service.exch.cmdata;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.dao.CrudDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.AbstractCrudService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.OPENCLOSE;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.turbo.dao.exch.GapOwnerConfDao;
import cn.com.dhcc.turbo.entity.exch.GapOwnerConf;
import cn.com.dhcc.turbo.entity.exch.GapUserConf;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncOperType;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.service.registry.GapUserConfService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.sync.SyncCenter;
import cn.com.dhcc.turbo.service.registry.vo.GapOwnerConfigSyncVo;

@Service
public class GapOwnerConfService extends AbstractCrudService<GapOwnerConf> {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.R);

	@Autowired
	private GapOwnerConfDao dao;
	
	@Autowired
	private GapUserConfService gapUserConfService;
	@Override
	public CrudDao<GapOwnerConf> getCrudDao() {
		return dao;
	}
	@Autowired
	private NodeInfoService nodeInfoService;
	@Autowired
	SyncCenter syncCenter;
	
	
	
	
	public void initGapConf() throws ServiceException{
		try {
			GapUserConf defalut=gapUserConfService.getDefaultGap();
			gapUserConfService.deleteAll();
			List<GapUserConf> data=this.getAllByUserAsUserConfig(nodeInfoService.getLocalNode().getNodeCode());
			if (data==null || data.isEmpty()) {
				return;
			}
			for (int i = 0; i < data.size(); i++) {
				GapUserConf gapUserConf=data.get(i);
				if (defalut==null) {
					if (i==0) {
						gapUserConf.setStatus("1");
					}else{
						gapUserConf.setStatus("0");
					}
				}else{
					if (gapUserConf.getGapOwner().equals(defalut.getGapOwner())) {
						gapUserConf.setStatus("1");
					}else{
						gapUserConf.setStatus("0");
					}
				}
				
			}
			gapUserConfService.insertOrUpdataUserConfList(data);
		}catch (ServiceException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		
		
	}
	
	public List<GapUserConf> getAllByUserAsUserConfig(String gapuser) throws ServiceException{
		try {
			return dao.getAllByUserAsUserConfig(gapuser);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	
	/**
	 * 根据节点的拥有者查询列表
	 * @param owner
	 * @return
	 * @throws NiceException 
	 * @throws ServiceException 
	 */
	public List<GapOwnerConf> getAllByOwner(String owner) throws ServiceException{
		try {
			return dao.getAllByOwner(owner);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		
	}
	/**
	 * 根据所有的网闸权限信息
	 * @param owner
	 * @return
	 * @throws NiceException 
	 * @throws ServiceException 
	 */
	public List<GapOwnerConf> getAllGapOwnerConf() throws ServiceException{
		try {
			return dao.list(null);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 根据节点的使用者查询列表
	 * @param gapUser
	 * @return
	 * @throws DaoException
	 */
	public List<GapOwnerConf> getAllByUser(String gapUser) throws ServiceException {
		try {
			return dao.getAllByUser(gapUser);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 根据节点的使用者查询列表
	 * @param gapUser
	 * @return
	 * @throws DaoException
	 */
	public GapOwnerConf getByUserAndOwner(String gapUser,String owner) throws ServiceException {
		try {
			return dao.getByUserAndOwner(gapUser,owner);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
   
	/**
	 * 根据用户节点编码 和 本节点编码建立网闸配置
	 * @param userids 用户节点的主键id
	 * @param ownerCode本节点编码
	 * @return
	 * @throws ServiceException 
	 */
	public List<GapOwnerConf> saveGapOwnerConfigByUserCode(String[] userCodes,String ownerCode) throws ServiceException{
		Date date=new Date();
		GapOwnerConf conf=null;
		List<GapOwnerConf> beans=new ArrayList<GapOwnerConf>();
		List<GapOwnerConf> beanInfo=new ArrayList<GapOwnerConf>();
		for (String userCode : userCodes) {
			conf = getByUserAndOwner(userCode, ownerCode);
			if(conf==null){
				conf=new GapOwnerConf();
				conf.setId(UUIDGenerator.getUUID());
				conf.setGapOwner(ownerCode);//设置网闸用户节点编码，不是主键
				conf.setGapUser(userCode);//网闸用户节点编码，不是主键
				conf.setMtime(date);//创建时间
				conf.setStatus(OPENCLOSE.OPEN.getStatus());
				beans.add(conf);
				insert(conf);
			}else{
				conf.setMtime(date);//修改时间
				conf.setStatus(OPENCLOSE.OPEN.getStatus());
				update(conf);
			}
		}
		for (GapOwnerConf bean : beans) {
			beanInfo.add(this.get(bean.getId()));
		}
		return beanInfo;
	}
	
	/**
	 * 根据用户节点编码 和 本节点编码删除网闸配置
	 * @param userids 用户节点的主键id
	 * @param ownerCode本节点编码
	 * @return
	 * @throws ServiceException 
	 */
	public String[] deleteGapOwnerConfigByUserCode(String[] userCodes,String ownerCode) throws ServiceException{
		for (String userCode : userCodes) {
			try {
				if (!userCode.equals(ownerCode)) {
					dao.deleteByUserAndOwner(userCode,ownerCode);
				}
			} catch (DaoException e) {
				throw new ServiceException(e);
			}
		}
		return userCodes;
	}
	/**
	 * 根据用户节点编码 和 本节点编码删除网闸配置
	 * @param userids 用户节点的主键id
	 * @param ownerCode本节点编码
	 * @return
	 * @throws ServiceException 
	 */
	public void deleteGapOwnerConfigByOwnerCode(String ownerCode) throws ServiceException{
		try {
			dao.deleteByOwner(ownerCode);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	

	/**
	 * 
	 * @param addCodes 增加的节点编码
	 * @param deleteCodes 删除的节点编码
	 *  @param localNode本节点
	 * @return
	 * @throws ServiceException
	 */
	public boolean updateGapOwnerConfig(String[] addCodes,String[] deleteCodes,NodeInfo localNode) throws ServiceException{
		if (deleteCodes!=null && deleteCodes.length>0) {
        	deleteGapOwnerConfigByUserCode(deleteCodes, localNode.getNodeCode());
		}
		if (addCodes!=null && addCodes.length>0) {
			saveGapOwnerConfigByUserCode(addCodes, localNode.getNodeCode());
		}
		//同步
		//1数据
		GapOwnerConfigSyncVo configSyncVo = new GapOwnerConfigSyncVo();
		configSyncVo.setOwnerCode(localNode.getNodeCode());
		List<GapOwnerConf>  listGapOwnerConf = getAllByOwner(localNode.getNodeCode());
		configSyncVo.setListGapOwnerConf(listGapOwnerConf);
		String dataContent = JsonUtil.toJson(configSyncVo);
		//2 目的节点
		List<NodeInfo> toNodes = getToNodes(listGapOwnerConf);
		if(!toNodes.isEmpty()&&StringUtils.hasText(dataContent)){
			syncCenter.registSyncTasksAndStart(UUIDGenerator.getUUID(), localNode, localNode, toNodes, dataContent, SyncOperType.UPDATE, SyncType.GAP_CONFIG, true);
		}
		return true;
	}
 
	public String getSyncDate() throws ServiceException{
		NodeInfo localNode = nodeInfoService.getLocalNode();
		GapOwnerConfigSyncVo configSyncVo = new GapOwnerConfigSyncVo();
		configSyncVo.setOwnerCode(localNode.getNodeCode());
		List<GapOwnerConf>  listGapOwnerConf = getAllByOwner(localNode.getNodeCode());
		configSyncVo.setListGapOwnerConf(listGapOwnerConf);
		String dataContent = JsonUtil.toJson(configSyncVo);
		return dataContent;
	}
	public List<NodeInfo> getToNodes(List<GapOwnerConf>  listGapOwnerConf) throws ServiceException{
		List<NodeInfo> toNodes = new ArrayList<NodeInfo>();
		if(CollectionUtil.hasElement(listGapOwnerConf)){
			for (Iterator<GapOwnerConf> iterator = listGapOwnerConf.iterator(); iterator.hasNext();) {
				GapOwnerConf gapOwnerConf =  iterator.next();
				toNodes.add(nodeInfoService.get(gapOwnerConf.getGapUserId()));
			}
		}
		return toNodes;
	}
}
